from django_redis import get_redis_connection
from rest_framework import serializers
from .utils import check_save_user_token
from users.models import User
from .models import OAuthQQUser

class QQAuthUserViewSerializers(serializers.Serializer):
    """openid 綁定用戶的序列化器"""
    # mobile password sms_code access_token
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='⼿机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, attrs):
        # 1. 把加密的openid 取出來加密
        # access_token = attrs['access_token'] # 如果key不存在直接報錯
        access_token = attrs.pop('access_token')
        openid = check_save_user_token(access_token)
        if openid is None:
            raise serializers.ValidationError('openid無效')

        # 1.1 把原本的 openid 重新添加到 attrs 字典(以備後續的create方法中綁定使用)
        attrs['openid'] = openid

        # 2. 校驗驗證碼
        # 校驗驗證碼
        redis_conn = get_redis_connection('verify_codes')
        mobile = attrs['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)

        # 向redis存儲數據時都是以字符串存儲的,取出來都是bytes類型

        if real_sms_code is None or attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('驗證碼錯誤')

        # 3. 拿手機號查詢 user表 如果能查到說明手機號已註冊,
        try:
            user = User.objects.get(mobile = mobile)
        except User.DoesNotExist:
            pass
        else:
            if user.check_password(attrs['password']) is False:
                raise serializers.ValidationError('密碼錯誤')
            else:
                # 如果用戶已存在,並且密碼也正確 把當前的user對象存儲到反序列化大字典中以備後期綁定使用
                attrs['user'] = user
        return attrs

    def create(self, validated_data):
        # 1. 獲取validated_data中的user,如果能取到user說明用戶已存在
        user = validated_data.get('user')
        if user is None:
            # 2. 如果vaildated_data 裏面沒有去除user,創建一個新用戶
            user = User(
                username = validated_data.get('mobile'),
                mobile = validated_data.get('mobile')
            )
            user.set_password(validated_data.get('password'))
            user.save()

        # 3. 把openid和user綁定
        OAuthQQUser.objects.create(
            openid = validated_data.get('openid'),
            user = user,
        )
        # 4. 把user返回
        return user
